﻿using System.Drawing;
using System.Windows.Forms;
using G.Runtime;

namespace GameDesigner.Source.Widgets
{
    class BoundVariableWidget : Widget
    {
        private readonly GameValue _BoundVariable;
        private readonly Control _Control;
        private readonly Point _Point;
        
        private string _DisplayableValue;
        private string _DisplayableName;

        public BoundVariableWidget(
            GameValue pBoundVariable, Control pControl, 
            Point pPoint, string name = null)
        {
            _BoundVariable = pBoundVariable;
            _Control = pControl;
            _Point = pPoint;
            _DisplayableName = ((name == null) ? _BoundVariable.Def.Name : name);
            _BoundVariable.ChangedEvent += this.OnVariableChanged;
            _BoundVariable.FireChangedEvent();
            _DisplayableValue = _DisplayableName + ": " + _BoundVariable.DisplayableValue;
            _Control.Paint += OnPaint;
        }
        
        public override void Dispose() 
        {
            _BoundVariable.ChangedEvent -= OnVariableChanged;
            _Control.Paint -= OnPaint;
        }

        public override Point Point
        {
            get { return _Point; }
        }

        public string Name
        {
            get { return _DisplayableName; }
        }
        
        private void OnVariableChanged(GameValue var)
        {
            _DisplayableValue = _DisplayableName + ": " + var.DisplayableValue;
            _Control.Invalidate();
        }

        protected override void OnPaint(object sender, PaintEventArgs e)
        {
            Font fn = new Font("Comic Sans MS", 12);
            SolidBrush solidBlack = new SolidBrush(Color.Black);
            e.Graphics.DrawString(_DisplayableValue, fn, solidBlack, _Point);
        }
    }
}
